package logic

import (
	"context"
	"errors"
	"log"
	"user_srv/cache"
	"user_srv/models"
	"user_srv/pkg"

	"user_srv/internal/svc"
	"user_srv/user"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginOrRegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginOrRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginOrRegisterLogic {
	return &LoginOrRegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginOrRegisterLogic) LoginOrRegister(in *user.LoginOrRegisterRequest) (*user.LoginOrRegisterResponse, error) {
	// todo: add your logic here and delete this line

	//查找用户账号是否存在
	var u models.User
	u.Mobile = in.Mobile
	err := u.GetUserByMobile()
	if err != nil {
		logx.Error("查找用户账号失败", err)
		return nil, err
	}

	//账号存在登录
	if u.ID > 0 {
		log.Println("用户账号存在，登录")
		//手机号密码登录
		if in.Password != "" {
			if u.Password != pkg.Md5(in.Password) {
				logx.Error("登录失败", errors.New("密码错误"))
				return nil, errors.New("密码错误")
			}
		} else {
			//手机号验证码登录
			get := cache.Rdb.Get(l.ctx, "sendSms"+"loginOrRegister"+in.Mobile)
			if get.Val() != in.Sms {
				logx.Error("登录失败", errors.New("短信验证码错误"))
				return nil, errors.New("短信验证码错误")
			}
		}

	} else {
		//账号不存注册
		get := cache.Rdb.Get(l.ctx, "sendSms"+"loginOrRegister"+in.Mobile)
		if get.Val() != in.Sms {
			logx.Error("注册失败", errors.New("短信验证码错误"))
			return nil, errors.New("短信验证码错误")
		}
		//注册账号
		log.Println("用户账号不存在，注册")
		if in.Password != "" {
			u.Password = pkg.Md5(in.Password)
		} else {
			logx.Error("注册密码未输入 默认设置成手机号")
			u.Password = pkg.Md5(in.Mobile)
		}

		err = u.RegisterUser()
		if err != nil {
			logx.Error("注册失败", err)
			return nil, err
		}
	}

	return &user.LoginOrRegisterResponse{UserId: int64(u.ID)}, nil
}
